/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 晓星航
 * Date: 2023-07-27
 * Time: 16:45
 */
//自己写的阻塞队列
//此处不考虑泛型
class MyBlockingQueue {
    private final int[] items = new int[1000];
    private int head = 0;
    private int tail = 0;
    private int size = 0;

    //入队列
    public void put (int value) throws InterruptedException {
        synchronized (this) {
            //这里的 while 是为了循环判断这里的队列到底是否已满 如果不满足就一直阻塞
            while (size == items.length) {
                //数组已满 ,此时要产生阻塞
                //return;
                this.wait();
            }
            items[tail] = value;
            tail++;
            if (tail >= items.length) {
                tail = 0;
            }
            size++;

            //这个notify 唤醒 take 中的wait
            this.notify();
        }
    }
    //出队列 - 先进先出
    public Integer take() throws InterruptedException {
        int result = 0;
        synchronized (this) {
            //这里的 while 是为了循环判断这里的队列到底是否为空 如果不满足就一直阻塞
            while (size == 0) {
                //队列为空 无法出元素
                //return null;
                this.wait();
            }
            result = items[head];
            head++;
            if (head >= items.length) {
                head = 0;
            }
            size--;

            //唤醒 put 中的 wait
            this.notify();
        }
        return result;
    }
}
public class ThreadDemo23 {
    public static void main(String[] args) throws InterruptedException {
//        MyBlockingQueue queue = new MyBlockingQueue();
//        queue.put(1);
//        queue.put(2);
//        queue.put(3);
//        queue.put(4);
//        queue.put(5);
//        int result = 0;
//        result = queue.take();
//        System.out.println("result: " + result);
//        result = queue.take();
//        System.out.println("result: " + result);
//        result = queue.take();
//        System.out.println("result: " + result);
//        result = queue.take();
//        System.out.println("result: " + result);
//        result = queue.take();
//        System.out.println("result: " + result);
        MyBlockingQueue queue = new MyBlockingQueue();
        Thread customer = new Thread(()->{
            while (true) {
                try {
                    int result = queue.take();
                    System.out.println("消费者：" + result);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        customer.start();

        Thread producer = new Thread(()->{
            int count = 0;
            while (true) {
                try {
                    System.out.println("生产：" + count);
                    queue.put(count);
                    count ++;
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        producer.start();

    }
}
